﻿#include "targetcli.h"

TargetCli::TargetCli(QString &id, STRUCT_TARGET_INFO &cfg, QList<IPC *> &ipcList, QObject *parent) :
    QObject(parent),
    m_proxyId(id),
    m_sock(),
    m_cfg(cfg),
    m_timer(),
    m_ipcList(ipcList),
    m_ipcArray(),
    m_snapArray(),
    m_nCountPeople(0)
{
    m_sock.connectToHost(m_cfg.ip, m_cfg.port);
    connect(&m_sock, SIGNAL(readyRead()), this, SLOT(onRead()));
    connect(&m_sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    m_timer.start(10000);
}

TargetCli::~TargetCli()
{
    m_timer.disconnect();
    m_sock.disconnect();
    m_sock.close();
}

void TargetCli::onRead()
{
    m_msg += m_sock.readAll();

    int index = m_msg.indexOf('$');
    if (index != -1)
    {
        QByteArray msg = m_msg.mid(0, index);
        QJsonParseError jsonErr;
        QJsonObject jsonObj;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(msg, &jsonErr);

        emit this->textRecv(msg);
        if (jsonErr.error == QJsonParseError::NoError && jsonDoc.isObject())
        {
            jsonObj = jsonDoc.object();

            if (jsonObj["id"].isNull())
            {
                WARNING_PRINT << "no id" << msg;
            }
            else
            {
                QString ip = jsonObj["id"].toString();
                int id = 0;
                foreach (IPC *ipc, m_ipcList)
                {
                    if (ipc->m_ipcInfo.ip == ip)
                    {
                        id = ipc->m_id.toInt();
                    }
                }

                if (!jsonObj["number"].isNull())
                {
                    int num = jsonObj["number"].toInt();
                    QJsonObject jsonSnd;

                    jsonSnd["estate_id"] = QString("").sprintf("%d", m_proxyId.toInt());
                    jsonSnd["device_id"] = QString("").sprintf("%s_%04d", m_proxyId.toLatin1().data(), id);
                    jsonSnd["function_name"] = "mult";
                    jsonSnd["create_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
                    jsonSnd["is_alarm"] = "false";
                    jsonSnd["pic_snap_list"] = m_snapArray[id];
                    jsonSnd["people_count"] = QString("").sprintf("%d", num);
                    jsonSnd["is_count_people"] = m_nCountPeople;    //增加的人流数量发给后台，并清空
                    m_nCountPeople = 0;

                    emit postReport(QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact));
                    emit postBigData(QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact));
                    m_snapArray[id] = QJsonArray();
                }
                else if (!jsonObj["alarm_number"].isNull())
                {
                    int num = jsonObj["alarm_number"].toInt();
                    QByteArray jpg = QByteArray::fromBase64(jsonObj["screenshot"].toString().toLatin1());
                    QString alarm_degree;
                    QJsonObject jsonSnd;

                    if (num >= m_cfg.alarm_threshold1)
                    {
                        alarm_degree = "first_degree";
                    }
                    else if (num >= m_cfg.alarm_threshold2)
                    {
                        alarm_degree = "second_degree";
                    }
                    else if (num >= m_cfg.alarm_threshold3)
                    {
                        alarm_degree = "third_degree";
                    }
                    else if (num >= m_cfg.alarm_threshold4)
                    {
                        alarm_degree = "fourth_degree";
                    }

                    jsonSnd["estate_id"] = QString("").sprintf("%d", m_proxyId.toInt());
                    jsonSnd["device_id"] = QString("").sprintf("%s_%04d", m_proxyId.toLatin1().data(), id);
                    jsonSnd["function_name"] = "mult";
                    jsonSnd["create_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
                    jsonSnd["pic_snap_origin"] = QString(QCryptographicHash::hash(jpg, QCryptographicHash::Md5).toHex());
                    jsonSnd["is_alarm"] = "true";
                    jsonSnd["event_type"] = "flow";
                    jsonSnd["people_count"] = QString("").sprintf("%d", num);
                    jsonSnd["alarm_degree"] = alarm_degree;

                    //DEBUG_PRINT << QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact);
                    emit postReport(QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact));
                    emit postBigData(QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact));
                    emit postPic(jpg);
                }
                else if (!jsonObj["distance"].isNull())
                {
                    int num = jsonObj["tailing_number"].toInt();
                    jsonObj["distance"].toInt();
                    QByteArray jpg = QByteArray::fromBase64(jsonObj["screenshot"].toString().toLatin1());
                    QJsonObject jsonSnd;

                    jsonSnd["estate_id"] = QString("").sprintf("%d", m_proxyId.toInt());
                    jsonSnd["device_id"] = QString("").sprintf("%s_%04d", m_proxyId.toLatin1().data(), id);
                    jsonSnd["function_name"] = "mult";
                    jsonSnd["create_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
                    jsonSnd["pic_snap_origin"] = QString(QCryptographicHash::hash(jpg, QCryptographicHash::Md5).toHex());
                    jsonSnd["is_alarm"] = "true";
                    jsonSnd["event_type"] = "stalker";
                    jsonSnd["people_count"] = QString("").sprintf("%d", num);
                    jsonSnd["alarm_degree"] = "fourth_degree";

                    //DEBUG_PRINT << QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact);
                    emit postReport(QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact));
                    emit postBigData(QJsonDocument(jsonSnd).toJson(QJsonDocument::Compact));
                    emit postPic(jpg);
                }
                else if (!jsonObj["snap"].isNull())
                {
                    QByteArray jpg = QByteArray::fromBase64(jsonObj["snap"].toString().toLatin1());
                    QJsonObject jsonSnap;

                    jsonSnap["pic"] = QString(QCryptographicHash::hash(jpg, QCryptographicHash::Md5).toHex());
                    jsonSnap["create_time"] = QTime::currentTime().toString("hh:mm:ss");

                    m_snapArray[id].append(jsonSnap);
                    emit postPic(jpg);
                }
                else if (!jsonObj["is_count_people"].isNull())
                {
                    //人流+1
                    int num = jsonObj["is_count_people"].toInt();
                    if (num > 0)
                    {
                        //人流数+1
                        m_nCountPeople++;
                    }
                }
            }
        }
        else
        {
            WARNING_PRINT << "recv unkown msg" << msg;
        }

        m_msg = m_msg.mid(index + 1);
    }
}

void TargetCli::onTimeout()
{
    if (m_sock.state() == QAbstractSocket::UnconnectedState)
    {
        m_ipcArray = QJsonArray();
        m_sock.connectToHost(m_cfg.ip, m_cfg.port);
        return ;
    }
    else if (m_sock.state() != QAbstractSocket::ConnectedState)
    {
        return ;
    }

    QJsonArray ipcArray;
    for (int i = 0; i < m_ipcList.size(); i++)
    {
        QJsonObject ipc;
        if ((m_ipcList[i]->m_ipcInfo.type & (1 << IPC_TYPE_TARGET)) != 0)
        {
            ipc.insert("id", i);
            ipc.insert("rtsp", QString("rtsp://%1:%2@%3/live/0/main").arg(m_ipcList[i]->m_ipcInfo.username,
                                                                          m_ipcList[i]->m_ipcInfo.password,
                                                                          m_ipcList[i]->m_ipcInfo.ip));
            ipc.insert("x", m_ipcList[i]->m_ipcInfo.motionStartX * (640 / 22));
            ipc.insert("y", m_ipcList[i]->m_ipcInfo.motionStartY * (480 / 18));
            ipc.insert("width", m_ipcList[i]->m_ipcInfo.motionWidth * (640 / 22));
            ipc.insert("height", m_ipcList[i]->m_ipcInfo.motionHeight * (480 / 18));
            ipcArray.append(ipc);
        }
    }

    if (m_ipcArray != ipcArray)
    {
        m_ipcArray = ipcArray;

        QJsonObject targetIpc;
        targetIpc.insert("gap", m_cfg.gap);
        targetIpc.insert("IPC", m_ipcArray);
        targetIpc.insert("alarm_distance", m_cfg.alarm_distance);
        targetIpc.insert("alarm_gap", m_cfg.alarm_gap);
        targetIpc.insert("threshold", m_cfg.alarm_threshold4);

        if (m_sock.isOpen() && m_sock.isWritable())
        {
            m_sock.write(QJsonDocument(targetIpc).toJson(QJsonDocument::Compact));
            DEBUG_PRINT << QJsonDocument(targetIpc).toJson(QJsonDocument::Compact);
        }

        m_snapArray.clear();
        for (int i = 0; i < m_ipcList.size(); i++)
        {
            m_snapArray.push_back(QJsonArray());
        }
    }
}

void TargetCli::onError(QAbstractSocket::SocketError err)
{
   // WARNING_PRINT << err;
}
